﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Xml;

namespace HuaXingSDK
{
    public class HXReply : HXEncryptXml
    {
        public string ChannelCode { get; }
        public string ChannelFlow { get; }
        public string TransCode { get; }
        public string ServerFlow { get; }
        public int ServerDate { get; }
        public int ServerTime { get; }
        public HXHeaderStatus Status { get; set; }
        public string ErrorCode { get; set; }
        public string ErrorMsg { get; set; }

        public string ReturnCode { get; set; }
        public string ReturnMsg { get; set; }

        public HXReply(string channelFlow, string transCode)
        {
            ChannelFlow = channelFlow;
            TransCode = transCode;
            ChannelCode = HXConfigs.渠道标识;
            var date = DateTime.UtcNow.AddHours(8);
            ServerDate = int.Parse(date.ToString("yyyyMMdd"));
            ServerTime = int.Parse(date.ToString("HHmmss"));
            ErrorCode = "0";
            ErrorMsg = "success";
            Status = HXHeaderStatus.受理成功;
            ServerFlow = Uilts.GetId(20);
        }

        protected override string[] GetHeader()
        {
            var ps = typeof(HXReply).GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
            return ps.Select(i => i.Name).ToArray();
        }

        protected override string[] GetBody()
        {
            var t = GetType();
            var header = GetHeader().ToList();
            header.Remove(nameof(TransCode));
            var names = new List<string>();
            var ps = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            foreach (var p in ps)
            {
                if (header.Contains(p.Name))
                    continue;
                names.Add(p.Name);
            }
            return names.ToArray();
        }

        protected override string[] GetEncrypt()
        {
            var body = GetBody();
            return body.Where(i => !nameof(TransCode).Equals(i, StringComparison.OrdinalIgnoreCase))
                .ToArray();
        }

        public override XmlDocument ToXml()
        {
            if (string.IsNullOrEmpty(TransCode))
                throw new HXException(nameof(TransCode) + "不能是空。");
            return base.ToXml();
        }

        protected override void OnNode(XmlNode parentNode, string name, object value)
        {
            if (value is HXHeaderStatus)
                value = (int) value;
            base.OnNode(parentNode, name, value);
        }
    }
}
